<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/7/29/029
 * Time: 12:53
 */

namespace App\Services;


use Auth;
use App\Models\CartItem;
class CartService
{
    public function get()
    {
        //取出用户购物车里的数据
        return Auth::user()->cartItems()->with(['productSku.product'])->get();
    }
    public function add($skuId,$amount)
    {
        $user = Auth::user();
        //从数据库中查询该商品是否存在购物车中
        if($item = $user->cartItems()->where('product_sku_id',$skuId)->first())
        {
            //如果存在直接加商品数量
            $item->update([
                'amount' => $item->amount +$amount,
            ]);
        }else{
            //不存在就新建一个购物车的记录
            $item = new CartItem(['amount'=>$amount]);
            $item->user()->associate($user);
            $item->productSku()->associate($skuId);
            $item->save();
        }
        return $item;
    }

    public function remove($skuIds)
    {
        //可以穿单个id，也可以传单个数组
        if(!is_array($skuIds))
        {
            $skuIds = [$skuIds];
        }
        Auth::user()->cartItems()->whereIn('product_sku_id',$skuIds)->delete();
    }
}